package sample.crawler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import sample.crawler.base.BaseTask;
import sample.enums.MapType;
import sample.model.Company;
import sample.utils.IndexUtils;
import sample.utils.Md5Utils;
import sample.utils.StringUtils;
import sample.utils.TencentUtils;

import java.net.URLEncoder;

public class TencentTask extends BaseTask {

    public TencentTask()
    {

    }
    public TencentTask(String url)
    {
        super.mapCode = MapType.tencent.getCode();

        this.url = url;
    }

    @Override
    public String getUrl(Integer pageNo) {
        //return TencentUtils.getUrl(keywords, area, pageSize, pageNo);
        //String url = "https://apis.map.qq.com/ws/place/v1/search?boundary=region({region},0)&key=SOLBZ-ZLPC4-LA3UM-DT4WE-5EO4K-6LBWE&keyword={keyword}&orderby=_distance&output=json&page_index={page_index}&page_size={page_size}&sig={sig}";
        String replaceUrl = url.replace("{region}", area).replace("{keyword}", keywords).replace("{page_index}", pageNo.toString()).replace("{page_size}", pageSize.toString());
        String sig = Md5Utils.md5(replaceUrl.replace("&sig={sig}", ""));
        replaceUrl = replaceUrl.replace("{sig}", sig).replace("region("+area+",0)", URLEncoder.encode("region("+area+",0)"));
        return replaceUrl;
    }

    @Override
    public Integer getTotalCount(JSONObject res) {
        return res.getInteger("count");
    }

    @Override
    public void fillTable(JSONObject jsonObject) throws Exception {
        if(jsonObject.getInteger("status") != 0) {
            throw new Exception(jsonObject.getString("message"));
        }
        JSONArray results = jsonObject.getJSONArray("data");
        if(results == null)
        {
            throw new Exception("no records");
        }
        for (Object o : results) {
            JSONObject target = (JSONObject) o;

            // 过滤排除关键字
            String name = target.getString("title");
            if(StringUtils.contains(name, exclusiveWords)) {
                continue;
            }

            // 过滤空电话
            String tel = target.getString("tel");
            if(filterTel && StringUtils.isEmpty(tel)) {
                continue;
            }

            JSONObject location = target.getJSONObject("location");
            StringBuffer locsb = new StringBuffer().append(location.getInteger("lat")).append(",").append(location.getInteger("lng"));

            JSONObject adInfo = target.getJSONObject("ad_info");
            qrTable.getItems().add(new Company(IndexUtils.getIndex() + "", tel , name, adInfo.getString("province")+ adInfo.getString("city") +adInfo.getString("district"), target.getString("address"), target.getString("category"),
                    keywords, MapType.map.get(mapCode), locsb.toString()));

        }
    }

}
